package touro.mancala.client.view;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JToolTip;

import touro.mancala.client.GameState;
import touro.mancala.client.Stone;
import touro.mancala.client.Store;

public class StoreView extends JComponent {

	private static final long serialVersionUID = -486459438508761691L;
	private Store store;
	ArrayList<Stone> stones;
	Image img;
	
	public StoreView(Store store) {
		this.store = store;
		try {
			img = ImageIO.read(ClassLoader.getSystemClassLoader().getResourceAsStream("client/grossman_store.jpg"));
		} catch (IOException e) {
		}	
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null, null);
		stones = store.getStones();
		int y = this.getHeight()/5;
		int index = 0;
		for (Stone s : stones) {
			StoneView view = new StoneView(s);
			y = paintStone(view, g, stones.size(), index, y);
			index++;
		}
		this.setToolTipText(" " + store.getSize() + " ");
	}
	
	@Override
	public JToolTip createToolTip() {
		JToolTip sizeStore = new JToolTip();
		sizeStore.setBackground(BoardView.BROWN);
		sizeStore.setTipText(" " + store.getSize() + " ");
		sizeStore.setForeground(Color.WHITE);
		sizeStore.setBorder(BorderFactory.createLineBorder(GameState.getGameState().getColor().darker(), 5));
		return sizeStore;
	}

	@Override
	public Point getToolTipLocation(MouseEvent arg0) {
		return new Point(3 * this.getWidth()/8, this.getHeight()/2);
	}

	private int paintStone(StoneView view, Graphics g, int numStones, int index, int yCoord) {
		int width = this.getWidth()/6;
		int height = width;
		int x = 0;
		int y = 0;
		int heightWholePit = this.getHeight();
		int heightPit = 3 *  heightWholePit/5;
		if (numStones * (height-2) > heightPit && heightPit!=0) {
			if (yCoord + height < 4 *  heightWholePit/5) {
				x = this.getWidth()/2 - 3 * (width/2);
				y = yCoord;
			} else {
				x = this.getWidth()/2 + width/2;
				int numStonesOnSecondSide = ((yCoord+height) - 4 * (heightWholePit/5))/ (height-2);
				int offset = (height-2) * (numStonesOnSecondSide);
				y = heightWholePit/5 + offset;
			}
		} else {
			x = this.getWidth()/2 - width/2;
			y = yCoord;
		}
		view.paintComponent(g, x, y, width, height);
		return yCoord += (height-2);
	}

	public Store getStore() {
		return store;
	}

}
